<template>
	<view class="p-[16px]">
		<u-form error-type="toast" ref="formRef" :model="formData" :rules="rules">
			<u-form-item prop="oldPassword">
				<u-input v-model="formData.oldPassword" prefix-icon="/static/password.svg" :prefixIconStyle="{fontSize:'24px',color:'#d81e06'}" clearable type="password" placeholder="请输入旧密码" border="none"></u-input>
			</u-form-item>
			<u-form-item prop="newPassword">
				<u-input v-model="formData.newPassword" prefix-icon="/static/password.svg" :prefixIconStyle="{fontSize:'24px',color:'#d81e06'}" clearable type="password" placeholder="请输入新密码" border="none"></u-input>
			</u-form-item>
			<u-form-item prop="newPassword2">
				<u-input v-model="formData.newPassword2" prefix-icon="/static/password.svg" :prefixIconStyle="{fontSize:'24px',color:'#d81e06'}" clearable type="password" placeholder="请确认新密码" border="none"></u-input>
			</u-form-item>
		</u-form>
		<u-gap height="40"></u-gap>
		<u-button @click="changePwd" color="#d81e06" size="large" shape="circle" text="提交"></u-button>
	</view>
</template>

<script setup>
	import {ref, unref, nextTick} from "vue";
	import * as api from "@/api.js";
	import {useUserStore} from "@/store/config.js";
	
	const store = useUserStore();
	
	const formRef = ref();
	const formData = ref({
		oldPassword: '',//老密码
		newPassword:'',//新密码
		newPassword2: '',//再次确认密码
	})
	
	const rules = {
		newPassword:[
			{
				required: true,
				message: '请输入旧密码',
				trigger: ['blur'],
			}
		],
		newPassword:[
			{
				required: true,
				message: '请输入密码',
				trigger: ['blur'],
			},
			{
				min:6,
				max:12,
				message: '长度在6-12个字符之间'
			},
			{
				validator: (rule, value, callback) => {
					return value.split(' ').length == 1;
				},
				message: '密码不能包含空格',
				trigger: ['blur'],
			},
			{
				validator: (rule, value, callback) => {
					return value !== formData.value.oldPassword;
				},
				message: '新密码不能和旧密码一样',
				trigger: ['blur'],
			}
		],
		newPassword2:[
			{
				required: true,
				message: '请确认新密码',
				trigger: ['blur'],
			},
			{
				validator: (rule, value, callback) => {
					return value === formData.value.newPassword;
				},
				message: '两次新密码不一致',
				trigger: ['blur'],
			}
		]
	}
	
	const changePwd = () => {
		formRef.value.validate().then(async res => {
			uni.showLoading();
			const result = await api.changePwd({userId:store.user.UserID,oldPassword:unref(formData).oldPassword,newPassword:unref(formData).newPassword});
			uni.hideLoading();
			await nextTick();
			if(result[1]) {
				uni.showToast({
					icon:'none',
					title:result[1]
				})
			} else {
				uni.showToast({
					icon:'success',
					title:'修改成功'
				})
				await new Promise(resolve => setTimeout(() => resolve(),800));
				uni.navigateBack();
			}
		}).catch(err => console.log(err))
	}
</script>

<style>
	page{
		background-color: #FFFFFF;
	}
</style>
